<template>
  <div class="sales-overview">
    <div class="page-container">
      <!-- 页面标题和日期筛选 -->
      <div class="page-header">
        <div class="header-content">
          <h1 class="page-title">销售概览统计</h1>
          <div class="date-filter">
            <a-range-picker
              v-model="dateRange"
              format="YYYY-MM-DD"
              :placeholder="['开始日期', '结束日期']"
              @change="onDateRangeChange"
              :allowClear="true"
              style="width: 240px; margin-right: 12px;"
            />
            <a-button type="primary" @click="refreshData" :loading="loading">
              <a-icon type="reload" />
              刷新数据
            </a-button>
          </div>
        </div>
      </div>

      <!-- 基础数据卡片 -->
      <div class="data-cards-grid">
        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title">
              今日销售额统计当天所有已确认订单的总金额。数据实时更新，反映当日业务表现。
            </template>
            <div class="card-title">
              今日销售额
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="card-value">
            <span class="value-number">{{ formatCurrency(overviewData.todaySales) }}</span>
            <span class="value-unit">元</span>
          </div>
        </div>
        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title">
              本周销售额统计本周（周一到周日）所有已确认订单的总金额。帮助了解周度业务表现趋势。
            </template>
            <div class="card-title">
              本周销售额
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="card-value">
            <span class="value-number text-blue">{{ formatCurrency(overviewData.weekSales) }}</span>
            <span class="value-unit">元</span>
          </div>
        </div>
        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title">
              本月销售额统计本月所有已确认订单的总金额。用于月度业绩评估和目标达成情况分析。
            </template>
            <div class="card-title">
              本月销售额
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="card-value">
            <span class="value-number text-blue">{{ formatCurrency(overviewData.monthSales) }}</span>
            <span class="value-unit">元</span>
          </div>
        </div>
        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title">
              本年销售额统计本年度所有已确认订单的总金额。反映年度整体业务规模和增长情况。
            </template>
            <div class="card-title">
              本年销售额
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="card-value">
            <span class="value-number text-blue">{{ formatCurrency(overviewData.yearSales) }}</span>
            <span class="value-unit">元</span>
          </div>
        </div>
      </div>

      <!-- 订单数量卡片 -->
      <div class="data-cards-grid">
        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title">
              今日订单数量统计当天创建的所有订单总数。反映当日业务活跃度和客户下单频次。
            </template>
            <div class="card-title">
              今日订单数量
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="card-value">
            <span class="value-number">{{ overviewData.todayOrderCount }}</span>
            <span class="value-unit">单</span>
          </div>
        </div>
        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title">
              本周订单数量统计本周（周一到周日）创建的所有订单总数。用于分析周度订单趋势和业务节奏。
            </template>
            <div class="card-title">
              本周订单数量
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="card-value">
            <span class="value-number text-blue">{{ overviewData.weekOrderCount }}</span>
            <span class="value-unit">单</span>
          </div>
        </div>
        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title">
              本月订单数量统计本月创建的所有订单总数。帮助评估月度业务量和客户活跃程度。
            </template>
            <div class="card-title">
              本月订单数量
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="card-value">
            <span class="value-number text-blue">{{ overviewData.monthOrderCount }}</span>
            <span class="value-unit">单</span>
          </div>
        </div>
        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title">
              本年订单数量统计本年度创建的所有订单总数。反映年度整体业务规模和市场表现。
            </template>
            <div class="card-title">
              本年订单数量
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="card-value">
            <span class="value-number text-blue">{{ overviewData.yearOrderCount }}</span>
            <span class="value-unit">单</span>
          </div>
        </div>
      </div>

      <!-- 统计指标 -->
      <div class="metrics-grid">
        <div class="metric-card">
          <a-tooltip placement="top">
            <template slot="title">
              平均订单金额反映客户的平均消费水平和订单价值。计算方式为总销售额除以订单总数，帮助分析客户购买力和产品定价策略。
            </template>
            <div class="card-title">
              平均订单金额
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="metric-content">
            <span class="metric-value">{{ formatCurrency(overviewData.avgOrderAmount) }} 元</span>
          </div>
        </div>
        <div class="metric-card">
          <a-tooltip placement="top">
            <template slot="title">
              月同比增长率显示本月销售额相比去年同月的增长情况。正值表示增长（绿色向上箭头），负值表示下降（红色向下箭头）。
              <br/><br/>
              <strong>计算公式：</strong><br/>
              (本月销售额 - 去年同月销售额) ÷ 去年同月销售额 × 100%
            </template>
            <div class="card-title">
              月同比增长率
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="metric-content">
            <span class="metric-value">{{ overviewData.monthGrowthRate }}%</span>
            <div class="trend-indicator" :class="overviewData.monthGrowthRate >= 0 ? 'trend-up' : 'trend-down'">
              <a-icon :type="overviewData.monthGrowthRate >= 0 ? 'arrow-up' : 'arrow-down'" />
              <span>{{ Math.abs(overviewData.monthGrowthRate) }}%</span>
            </div>
          </div>
          <div class="last-year-info" v-if="overviewData.lastYearMonthSales">
            去年同月: {{ formatCurrency(overviewData.lastYearMonthSales) }}元
          </div>
        </div>
        <div class="metric-card">
          <a-tooltip placement="top">
            <template slot="title">
              年同比增长率显示本年销售额相比去年同期的增长情况。帮助评估年度业务发展趋势和增长质量。
              <br/><br/>
              <strong>计算公式：</strong><br/>
              (本年销售额 - 去年同期销售额) ÷ 去年同期销售额 × 100%
            </template>
            <div class="card-title">
              年同比增长率
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="metric-content">
            <span class="metric-value">{{ overviewData.yearGrowthRate }}%</span>
            <div class="trend-indicator" :class="overviewData.yearGrowthRate >= 0 ? 'trend-up' : 'trend-down'">
              <a-icon :type="overviewData.yearGrowthRate >= 0 ? 'arrow-up' : 'arrow-down'" />
              <span>{{ Math.abs(overviewData.yearGrowthRate) }}%</span>
            </div>
          </div>
          <div class="last-year-info" v-if="overviewData.lastYearYearSales">
            去年同期: {{ formatCurrency(overviewData.lastYearYearSales) }}元
          </div>
        </div>
      </div>

      <!-- 图表区域 -->
      <div class="charts-grid">
        <div class="chart-card">
          <a-tooltip placement="top">
            <template slot="title">
              销售趋势图展示一段时间内的销售金额和订单数量变化趋势。柱状图显示销售金额，折线图显示订单数量，帮助分析业务发展规律和季节性特征。
            </template>
            <h3 class="chart-title">
              销售趋势
              <a-icon type="question-circle" style="color: #999; font-size: 14px; margin-left: 8px" />
            </h3>
          </a-tooltip>
          <div ref="trendChart" class="chart-container"></div>
        </div>
        <div class="chart-card">
          <a-tooltip placement="top">
            <template slot="title">
              订单状态分布饼图展示不同订单状态的数量占比。包括待处理、已确认、已发货、已完成等状态，帮助了解订单处理效率和业务流程状况。
            </template>
            <h3 class="chart-title">
              订单状态分布
              <a-icon type="question-circle" style="color: #999; font-size: 14px; margin-left: 8px" />
            </h3>
          </a-tooltip>
          <div ref="statusChart" class="chart-container"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getSalesOverview } from '@/api/oms/statistics'
import * as echarts from 'echarts'
import moment from 'moment'

export default {
  name: 'SalesOverview',
  data() {
    return {
      loading: false,
      dateRange: [],
      overviewData: {
        todaySales: 0,
        weekSales: 0,
        monthSales: 0,
        yearSales: 0,
        todayOrderCount: 0,
        weekOrderCount: 0,
        monthOrderCount: 0,
        yearOrderCount: 0,
        avgOrderAmount: 0,
        monthGrowthRate: 0,
        yearGrowthRate: 0,
        trendData: [],
        statusDistribution: [],
      },
      trendChart: null,
      statusChart: null,
    }
  },
  mounted() {
    this.initCharts()
    this.loadData()
  },
  beforeDestroy() {
    if (this.trendChart) {
      this.trendChart.dispose()
    }
    if (this.statusChart) {
      this.statusChart.dispose()
    }
  },
  methods: {
    async loadData() {
      try {
        this.loading = true
        const params = {}
        if (this.dateRange && this.dateRange.length === 2) {
          params.startDate = moment(this.dateRange[0]).format('YYYY-MM-DD')
          params.endDate = moment(this.dateRange[1]).format('YYYY-MM-DD')
        }

        const response = await getSalesOverview(params)
        if (response.success) {
          this.overviewData = response.result || {}
          this.updateCharts()
        } else {
          this.$message.error(response.message || '获取数据失败')
        }
      } catch (error) {
        console.error('加载销售概览数据失败:', error)
        this.$message.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },

    initCharts() {
      // 初始化趋势图表
      this.trendChart = echarts.init(this.$refs.trendChart)

      // 初始化状态分布图表
      this.statusChart = echarts.init(this.$refs.statusChart)

      // 监听窗口大小变化
      window.addEventListener('resize', this.handleResize)
    },

    updateCharts() {
      this.updateTrendChart()
      this.updateStatusChart()
    },

    updateTrendChart() {
      if (!this.trendChart || !this.overviewData.trendData) return

      const trendData = this.overviewData.trendData || []
      const dates = trendData.map((item) => item.date)
      const amounts = trendData.map((item) => item.amount)
      const orderCounts = trendData.map((item) => item.orderCount)

      const option = {
        title: {
          text: '销售趋势',
          left: 'center',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
        },
        legend: {
          data: ['销售额', '订单数量'],
          top: 30,
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisPointer: {
            type: 'shadow',
          },
        },
        yAxis: [
          {
            type: 'value',
            name: '销售额(元)',
            position: 'left',
            axisLabel: {
              formatter: '{value}',
            },
          },
          {
            type: 'value',
            name: '订单数量(单)',
            position: 'right',
            axisLabel: {
              formatter: '{value}',
            },
          },
        ],
        series: [
          {
            name: '销售额',
            type: 'bar',
            yAxisIndex: 0,
            data: amounts,
            itemStyle: {
              color: '#1890ff',
            },
          },
          {
            name: '订单数量',
            type: 'line',
            yAxisIndex: 1,
            data: orderCounts,
            itemStyle: {
              color: '#52c41a',
            },
          },
        ],
      }

      this.trendChart.setOption(option)
    },

    updateStatusChart() {
      if (!this.statusChart || !this.overviewData.statusDistribution) return

      const statusData = this.overviewData.statusDistribution || []
      const pieData = statusData.map((item) => ({
        name: item.statusName,
        value: item.count,
      }))

      const option = {
        title: {
          text: '订单状态分布',
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: 'middle',
        },
        series: [
          {
            name: '订单状态',
            type: 'pie',
            radius: '50%',
            data: pieData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      }

      this.statusChart.setOption(option)
    },

    getGrowthRateStyle(rate) {
      if (rate > 0) {
        return { color: '#3f8600' }
      } else if (rate < 0) {
        return { color: '#cf1322' }
      } else {
        return { color: '#666' }
      }
    },

    getGrowthIcon(rate) {
      if (rate === null || rate === undefined) return 'minus'
      return rate >= 0 ? 'rise' : 'fall'
    },
    formatCurrency(value) {
      if (!value) return '0.00'
      return Number(value).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      })
    },

    onDateRangeChange(dates) {
      this.dateRange = dates
      if (dates && dates.length === 2) {
        this.loadData()
      }
    },

    refreshData() {
      this.loadData()
    },

    handleResize() {
      if (this.trendChart) {
        this.trendChart.resize()
      }
      if (this.statusChart) {
        this.statusChart.resize()
      }
    },
  },
}
</script>

<style lang="less" scoped>
.sales-overview {
  min-height: 100vh;
  background: #f5f7fa;

  .page-container {
    max-width: 100vw;
    max-height: 100vh;
    margin: 0 auto;
    padding: 20px;
  }

  .page-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 16px;
    padding: 24px 32px;
    margin-bottom: 24px;
    box-shadow: 0 8px 32px rgba(102, 126, 234, 0.15);

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .page-title {
        font-size: 28px;
        font-weight: 600;
        color: #ffffff;
        margin: 0;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }

      .date-filter {
        display: flex;
        align-items: center;
        gap: 12px;

        .ant-btn-primary {
          background: rgba(255, 255, 255, 0.2);
          border: 1px solid rgba(255, 255, 255, 0.3);
          border-radius: 8px;
          font-weight: 500;
          backdrop-filter: blur(10px);
          transition: all 0.3s ease;

          &:hover {
            background: rgba(255, 255, 255, 0.3);
            border-color: rgba(255, 255, 255, 0.5);
            transform: translateY(-1px);
          }
        }

        .ant-calendar-picker {
          .ant-calendar-picker-input {
            background: rgba(255, 255, 255, 0.9);
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 8px;
            backdrop-filter: blur(10px);

            &:hover {
              border-color: rgba(255, 255, 255, 0.5);
            }
          }
        }
      }
    }
  }

  .data-cards-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 20px;

    .data-card {
      background: #ffffff;
      border-radius: 12px;
      padding: 20px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
        transform: translateY(-2px);
      }

      .card-title {
        font-size: 14px;
        color: #909399;
        margin-bottom: 12px;
      }

      .card-value {
        display: flex;
        align-items: baseline;

        .value-number {
          font-size: 24px;
          font-weight: 600;
          color: #303133;

          &.text-blue {
            color: #3b82f6;
          }
        }

        .value-unit {
          font-size: 14px;
          color: #909399;
          margin-left: 4px;
        }
      }
    }
  }

  .metrics-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-bottom: 20px;

    .metric-card {
      background: #ffffff;
      border-radius: 12px;
      padding: 20px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
        transform: translateY(-2px);
      }

      .card-title {
        font-size: 14px;
        color: #909399;
        margin-bottom: 12px;
      }

      .metric-content {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .metric-value {
          font-size: 24px;
          font-weight: 600;
          color: #303133;
        }

        .trend-indicator {
          display: flex;
          align-items: center;
          gap: 4px;
          font-size: 14px;
          font-weight: 500;

          &.trend-up {
            color: #67c23a;
          }

          &.trend-down {
            color: #f56c6c;
          }
        }
      }

      .last-year-info {
        margin-top: 8px;
        font-size: 12px;
        color: #909399;
      }
    }
  }

  .charts-grid {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 16px;

    .chart-card {
      background: #ffffff;
      border-radius: 12px;
      padding: 20px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

      .chart-title {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
        margin: 0 0 12px 0;
      }

      .chart-container {
        height: 360px;
      }
    }
  }
}
</style>
